import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo, getUserDetailById } from '@/api/user.js'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state, token) {
      state.token = ''
      removeToken()
    },
    getProfile(state, info) {
      state.userInfo = info
    },
    removeProfile(state) {
      state.token = ''
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, loginForm) {
      const res = await login(loginForm)
      console.log('获取到的token是', res.data)
      context.commit('updateToken', res.data)
    },

    async getUserInfo(context) {
      try {
        const res = await getInfo()
        console.log('11111111', res.data)
        const res1 = await getUserDetailById(res.data.userId)
        context.commit('getProfile', { ...res.data, ...res1.data })
        return res.data.roles.menus
      } catch (error) {
        console.log(error)
      }
    },

    logout(context) {
      context.commit('removeProfile')
      context.commit('removeToken')
      resetRouter()
    }
  }
}
